package com.hn658.user.sync.auth;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.hn658.framework.shared.utils.JsonMapper;
import com.hn658.user.sync.Env;
import com.hn658.user.sync.httpClient.HttpHelper;
import com.hn658.user.sync.httpClient.HttpRequest;
import com.hn658.user.sync.httpClient.HttpResponse;

public class AuthHelper {
	
	private static String accessToken = null;
	
	private static Integer cacheTime = 1000 * 60 * 60 * 2;
	
	private static long currentTime = 0 + cacheTime +1;
	
	private static long lastTime = 0;
	
	private static HttpRequest httpRequest=new HttpRequest(null);
	
	private static JsonMapper mapper = JsonMapper.nonEmptyMapper();
	
	private static Lock lock = new ReentrantLock();
	
	public static String getAccessToken() {
		if(lastTime != 0){
			currentTime = System.currentTimeMillis();
		}
		if(accessToken==null){
			lock.lock();
			try{
				if(currentTime - lastTime >= cacheTime){
					String url = Env.OAPI_HOST + "/gettoken?" + 
							"corpid=" + Env.CORP_ID + "&corpsecret=" + Env.SECRET;
					httpRequest.setUrl(url);
					httpRequest.setMethod(HttpRequest.METHOD_GET);
					HttpResponse response = HttpHelper.httpGet(httpRequest);
					String stringResult = response.getStringResult();
					HttpResponse fromJson = mapper.fromJson(stringResult,HttpResponse.class);
					accessToken=fromJson.getAccess_token();
					currentTime = System.currentTimeMillis();
					lastTime = System.currentTimeMillis();
				}
			}finally{
				lock.unlock();
			}
		}
		return accessToken;
	}

}
